package com.budwk.app.sys.commons.task.job;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.fetchdata.models.FetchData_emergency;
import com.budwk.app.fetchdata.services.FetchdataEmergencyService;
import com.budwk.app.miniapp.utils.AddressUtils;
import com.budwk.starter.job.annotation.SJob;
import lombok.extern.slf4j.Slf4j;
import org.nutz.dao.Cnd;
import org.nutz.ioc.impl.PropertiesProxy;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;


import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;


@Slf4j
@IocBean(name = "pullWaterConservancyService",singleton = false)
public class PullWaterConservancyService {

    @Inject
    private FetchdataEmergencyService wxSpiderEmergencyInformationService;
    @Inject
    private PropertiesProxy propertiesProxy;


    /**
     * 贵州省水利厅 山洪预警
     * @return
     */
     @SJob("waterconservancy")
    public void waterconservancy(String taskId, String params) {
        try {

            System.out.println("贵州省水利厅 山洪预警");

            int pageNumber=1,pageSize=50;
            List<FetchData_emergency> warningBoList = new ArrayList<>();
            String token =getOauthToken();
            if (token == null) {
                System.out.println("获取token出错");
            }
            token = "Bearer " + token;

            String requestUrl ="http://58.42.237.172:8188/api/station-service/regionWarning/infoList";
            Date newday = new Date();
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            String times =df.format(newday);
            for (int m = 0; m < 5; m++) {
                if(m>0) {
                    newday.setHours(newday.getHours() - 24);
                }
                times =df.format(newday);
                while (true) {

                    JSONObject jsonCode = new JSONObject();
                    JSONObject pageData = new JSONObject();
                    JSONObject regionParam = new JSONObject();
                    pageData.put("pageSize",20);
                    pageData.put("pageNow", pageNumber);
                    regionParam.put("startTime", times);
                    regionParam.put("adcd", "520000000000000");
                    String[] statuses={"0", "1", "2", "3", "4", "5", "6", "7"};
                    regionParam.put("statuses",  statuses);
                    jsonCode.put("pageData",pageData);
                    jsonCode.put("regionParam",regionParam);
                    String result =HttpRequest.post(requestUrl).header("Authorization",token).body(jsonCode.toJSONString()).execute().body();
                    JSONObject jsonObject = JSONObject.parseObject(result);
                    Integer code = jsonObject.getInteger("code");
                    String  msg = jsonObject.getString("msg");
                    JSONObject dataJson = jsonObject.getJSONObject("data");
                    if(code!=0)
                    {
                        System.out.println("获取水利厅接口数据出错"+msg);
                        break;
                    }
                    int pageCount = dataJson.getInteger("pages");
                    if (pageNumber > pageCount) {
                        break;
                    }
                    JSONArray listJson = dataJson.getJSONArray("source");
                    for (int i = 0; i < listJson.size(); i++) {
                        JSONObject item = listJson.getJSONObject(i);
                        FetchData_emergency warningBo = new FetchData_emergency();

                        String title=item.getString("city")+item.getString("county")+item.getString("town")+item.getString("warnName");
                        warningBo.setInformationtitle(title);//标题
                        warningBo.setReleasetime(((Timestamp) item.getTimestamp("warnDT"))); //发布时间
                        FetchData_emergency vo = wxSpiderEmergencyInformationService.fetch(Cnd.where(FetchData_emergency::getInformationtitle,"=",warningBo.getInformationtitle())
                                .and(FetchData_emergency::getReleasetime,"=",warningBo.getReleasetime()));
                        if (ObjectUtil.isEmpty(vo)) {
                            try {

                                warningBo.setInformationcontent(item.getString("warnContent"));//内容
                                warningBo.setInformationchannels("贵州省水利厅");//信息来源

                                warningBo.setInformationmedia("贵州省水利厅");
                                warningBo.setDisaster_status("灾害");
                                warningBo.setProvince("贵州省");
                                warningBo.setCity(item.getString("city"));
                                warningBo.setDistrict(item.getString("county"));
                                warningBo.setStreet(item.getString("town"));
                                warningBo.setDisaster_address("贵州省" + item.getString("city") + item.getString("county")+item.getString("town"));
                                warningBo.setLatitude(item.getString("lttd"));
                                warningBo.setLongitude(item.getString("lgtd"));
                                warningBo.setDisaster_type("山洪预警");
                                String warnName=item.getString("warnName");
                                if(warnName.indexOf("(")>0&&warnName.indexOf(")")>0) //等级，准备转移，立即转移  //白纸厂二组(准备转移)
                                {
                                    warningBo.setDisaster_class(warnName.substring(warnName.indexOf("(")+1,warnName.indexOf(")")));
                                }
                                //没有类型的再处理
                                warningBo.setPicurl("other.png");
                                warningBo.setAddperson("祥云AI");
                                warningBo.setAddphone("15555555555");
                                //添加人等
                                Date day = new Date();
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                warningBo.setAddtime(sdf.format(day));
                                warningBo.setIsshow("1");//不显示
                                warningBoList.add(warningBo);
                            } catch(Exception e) {
                                e.printStackTrace();
                            }

                        }
                    }
                    pageNumber++;
                    if (pageNumber > pageCount) {
                        break;
                    }
                }
            }
            if(CollectionUtil.isNotEmpty(warningBoList)){
                wxSpiderEmergencyInformationService.fastInsert(warningBoList);
            }
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    private String getOauthToken() {
        String requestUrl = "http://58.42.237.172:8188/api/system/oauth/token?username=xytb&password=vJZzem7jr78hWGLAmdmf5w==&code=0&grant_type=password&scope=server";
        try {
            String loginresult = HttpRequest.post(requestUrl).header("terminal","companion").execute().body();
            JSONObject jsonObject = JSONObject.parseObject(loginresult);
            System.out.println("access_token: "+jsonObject.getString("access_token"));
            return  jsonObject.getString("access_token");
        } catch(Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}
